// miniprogram/pages/homePage/usedGoods/addGoods/addGoods.js

//获取应用实例
const app = getApp()
const db = wx.cloud.database()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        formWarn: false,
        goods: {
            title: "",
            intro: "",
            category: "",
            price: null,
            images: [],
            merchant: ""
        },
        show: false,
        actions: [
            {
                name: '生活百货'
            },
            {
                name: '服装鞋帽'
            },
            {
                name: '电器',
            },
            {
                name: '美妆',
            },
            {
                name: '数码设备',
            },
            {
                name: '运动户外',
            },
            {
                name: '零食水果',
            },
            {
                name: '其它',
            }
        ],
        fileList: []

    },

    inputChange(e) {
        if (e.currentTarget.dataset.item == "title") {
            this.data.goods.title = e.detail
        } else if (e.currentTarget.dataset.item == "intro") {
            this.data.goods.intro = e.detail
        } else if (e.currentTarget.dataset.item == "price") {
            this.data.goods.price = e.detail++
        }
        // console.log(e)
        // console.log(e.currentTarget.dataset.item)
        // console.log(e.detail)
    },
    upload() {
        const that = this;
        try {
            this.data.fileList.map(item => {
                const filePath = item.url
                let name = new Date().getTime().toString()
                // 上传图片
                const cloudPath = "usedGoods/" + name + filePath.match(/\.[^.]+?$/)[0]
                wx.cloud.uploadFile({
                    cloudPath,
                    filePath,
                    success: res => {
                        // console.log('[上传文件] 成功：', res.fileID)
                        that.data.goods.images.push(res.fileID)
                        if (that.data.goods.images.length == that.data.fileList.length) {
                            wx.cloud.callFunction({
                                name: 'addusedGoods',
                                data: {
                                    data: that.data.goods
                                }
                            }).then(res0 => {
                                wx.navigateTo({
                                    url: '/pages/homePage/usedGoods/details/details',
                                    success: function (res) {
                                        // 通过eventChannel向被打开页面传送数据
                                        res.eventChannel.emit('to_details', {
                                            mes: res0.result,
                                            status: "2"
                                        })
                                    }
                                })
                            })
                        }

                    },
                    fail: e => {
                        wx.showToast({
                            icon: 'none',
                            title: '上传失败',
                        })
                    }
                })
            })
        } catch (error) {
            console.error(error);
        }
    },
    submit() {
        this.data.goods.merchant = app.globalData.userInfo.nickName
        this.data.goods.avatarUrl = app.globalData.userInfo.avatarUrl

        for (let item in this.data.goods) {
            if (!this.data.fileList || item != "images" && !this.data.goods[item]) {
                // console.log(item)
                this.setData({
                    formWarn: true
                })
                return setTimeout(() => {
                    this.setData({
                        formWarn: false
                    })
                }, 2000)
            }
        }

        wx.showLoading({
            mask: true,
            title: '上传中',
        })
        this.upload()
    },
    // vant-ui
    categoryList() {
        this.setData({
            show: true,
        })
    },
    onClose() {
        this.setData({ show: false });
    },

    onSelect(event) {
        this.data.goods.category = event.detail.name
        this.setData({
            goods: this.data.goods
        })
    },
    afterRead(event) {
        const { file } = event.detail;
        const that = this;
        wx.chooseImage({
            count: 3,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {
                const { fileList = [] } = that.data;
                res.tempFilePaths.map(item => {
                    fileList.push({ ...file, url: item, isImage: true });
                })
                that.setData({
                    fileList
                })
            },
            fail: e => {
                console.error(e)
            }
        })
    },
    deleteImage(e) {
        // console.log(e.detail.index)
        const { fileList = [] } = this.data;
        fileList.splice(e.detail.index, 1)
        this.setData({ fileList })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})